package cn.yzgy.yzgyoa.common.service.impl;

import cn.yzgy.yzgyoa.common.annotation.SysDict;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 字典服务
 *
 * @author Yqsen
 * @since 2021-04-21 16:55:59
 */
@Slf4j
@Service
public class SysDictService {

    @Autowired
    private SysDictValueServiceImpl dictValueService;

    /**
     * 将List对象内的对象进行字典翻译
     *
     * @param list 对象
     * @return 经过字典翻译后的对象
     */
    public List<JSONObject> injectDictList(Object list) {
        //列表形式的数据
        List<JSONObject> result = new ArrayList<>();
        for (Object item : (List) list) {
            JSONObject jsonObject = (JSONObject) injectDictObject(item);
            result.add(jsonObject);
        }
        return result;
    }

    public Object injectDictObject(Object obj) {
        JSONObject jsonObject = (JSONObject) JSON.toJSON(obj);
        for (Field field : getAllFields(obj)) {
            if (field.getAnnotation(SysDict.class) != null) {
                String dictCode = field.getAnnotation(SysDict.class).dictCode();
                String dictSuffix = field.getAnnotation(SysDict.class).dictShowSuffix();
                String dictValue = jsonObject.getString(field.getName());
                if (field.getType() == Boolean.class) {
                    dictValue = "true".equals(dictValue) ? "1" : "0";
                }
                if (dictCode == null) {
                    dictCode= "";
                }
                if( dictValue == null || "".equals(dictValue)){
                    dictValue= "";
                }
                String dictText = dictValueService.getDictValue(dictCode, dictValue);
                log.info("字典Code：{} 待查值：{} 查询结果：{}", dictCode, dictValue, dictText);
                jsonObject.put(field.getName() + dictSuffix,
                        dictText != null ? dictText : "" + dictValue);
            }
        }
        return jsonObject;
    }

    /**
     * 获取某个类及其基类的所有属性
     *
     * @param obj 对象
     * @return 所有属性
     */
    public static Field[] getAllFields(Object obj) {
        Class<?> clazz = obj.getClass();
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null) {
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        fieldList.toArray(fields);
        return fields;
    }

}
